package com.dailyblue.java.servlet.controller;

import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

// 利用反射改写了Servlet，使得不同请求进入一个Servlet类，访问不同方法
@WebServlet("/reflection")
public class ReflectionController extends HttpServlet {

    @SneakyThrows
    // 所有的请求都会进入这个方法
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 通过反射的机制让它转发到指定方法中
        // 用户发送一个请求，这个请求就是要访问的方法名
        String methodName = req.getParameter("type");
        // 原始的写法
        /*if (methodName.equals("a")) {
            a(req, resp);
        } else if (methodName.equals("b")) {
            b(req, resp);
        }*/
        Class c = this.getClass();
        Method method = c.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
        method.invoke(this, req, resp);
    }

    public void a(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("aa");
    }

    public void b(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("bb");
    }
}
